package com.b2b.util;

import com.b2b.exception.CustomException;
import com.b2b.model.ContractDto;
import com.b2b.model.entity.Contract;
import com.b2b.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ContractUtil {
    private final ContractService contractService;
    @Autowired
    public ContractUtil(ContractService contractService){
        this.contractService = contractService;
    }

    public List<ContractDto> getAll(){
        List<Contract> contractList = contractService.selectAll();
        List<ContractDto> contractDtoList = new ArrayList<>();
        for (int i = 0; i < contractList.size(); i++) {
            contractDtoList.add(getContractDto(contractList.get(i)));
        }
        return contractDtoList;
    }

    public List<ContractDto> getContractDtoList(List<Contract> contractList){
        List<ContractDto> contractDtoList = new ArrayList<>();
        for (int i = 0; i < contractList.size(); i++) {
            contractDtoList.add(getContractDto(contractList.get(i)));
        }
        return contractDtoList;
    }
    public Integer addContract(ContractDto contractDto){
        Contract contract = getContract(contractDto);
        Integer count = contractService.insert(contract);
        if (count<=0){
            return count;
        }else {
            count = contract.getContractId();
            return count;
        }
    }
    public ContractDto getByName(String fileName){
        Contract contract = new Contract();
        contract.setFileName(fileName);
        Integer count = contractService.selectCount(contract);
        if (count<=0){
            throw new CustomException("查询失败(Query Failure)");
        }else {
            contract = contractService.selectOne(contract);
            return getContractDto(contract);
        }
    }


    public Contract getContract(ContractDto contractDto){
        Contract contract = new Contract();
        contract.setContractId(contractDto.getContractId());
        contract.setCompanyId(contractDto.getCompanyId());
        contract.setFileUrl(contractDto.getFileUrl());
        contract.setFileName(contractDto.getFileName());
        contract.setVisibility(contractDto.getVisibility());

        return contract;
    }

    public ContractDto getContractDto(Contract contract){
        ContractDto contractDto = new ContractDto();

        contractDto.setContractId(contract.getContractId());
        contractDto.setCompanyId(contract.getCompanyId());
        contractDto.setFileUrl(contract.getFileUrl());
        contractDto.setFileName(contract.getFileName());
        contractDto.setVisibility(contract.getVisibility());

        return contractDto;

    }
}
